package com.joysuch.wwyt.risk.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.joysuch.wwyt.config.RedisClient;
import com.joysuch.wwyt.core.bean.SimpleSelectListBean;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.constant.Constants;
import com.joysuch.wwyt.core.enums.BaseConfigCodes;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.mh.service.MonitorPointDataWebSocketService;
import com.joysuch.wwyt.risk.bean.*;
import com.joysuch.wwyt.risk.entity.*;
import com.joysuch.wwyt.risk.entity.dto.RiskDynamicConfigDto;
import com.joysuch.wwyt.risk.entity.vo.RiskDynamicConfigBatchSaveVo;
import com.joysuch.wwyt.risk.repository.*;
import com.joysuch.wwyt.risk.service.RiskEvaluationTempleService;
import com.joysuch.wwyt.workflow.WorkFlowConstants;
import com.joysuch.wwyt.workflow.entity.WorkFlowOption;
import com.joysuch.wwyt.workflow.entity.WorkFlowOptionType;
import com.joysuch.wwyt.workflow.entity.WorkFlowProcess;
import com.joysuch.wwyt.workflow.repository.WorkFlowOptionDao;
import com.joysuch.wwyt.workflow.repository.WorkFlowOptionTypeDao;
import com.joysuch.wwyt.workflow.repository.WorkFlowProcessDao;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.transaction.Transactional;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class RiskEvaluationTempleServiceImpl implements RiskEvaluationTempleService {

    @Autowired
    private RiskEvaluationControlDao riskEvaluationControlDao;
    @Autowired
    private RiskEvaluationCorrectionRuleDao correctionRuleDao;
    @Autowired
    private RiskEvaluationListFieldDao listFieldDao;
    @Autowired
    private RiskEvaluationAnalyzeWayDao analyzeWayDao;
    @Autowired
    private RiskEvaluationAnalyzeMethodDao analyzeMethodDao;
    @Autowired
    private RiskEvaluationTargetTypeDao targetTypeDao;
    @Autowired
    private RiskEvaluationTargetItemDao targetItemDao;
    @Autowired
    private RiskPointEvaluationBusinessDao riskPointEvaluationBusinessDao;
    @Autowired
    private RiskDynamicConfigDao riskDynamicConfigDao;
    @Autowired
    private WorkFlowOptionTypeDao workFlowOptionTypeDao;
    @Autowired
    private WorkFlowOptionDao workFlowOptionDao;
    @Autowired
    private WorkFlowProcessDao workFlowProcessDao;
    @Autowired
    private MonitorPointDataWebSocketService monitorPointDataWebSocketService;
    @Autowired
    private RedisClient redisClient;

    /**
     * 设置基础配置开关状态
     *
     * @param name
     * @param state
     * @return
     */
    @Override
    public RiskEvaluationControl editSwitchState(String name, Integer state) {
        RiskEvaluationControl control = riskEvaluationControlDao.findByName(name);
        if (control != null) {
            control.setSwitchState(state);
        } else {
            //没有 默认新增
            control = new RiskEvaluationControl();
            control.setName(name);
            control.setSwitchState(state);
        }
        RiskEvaluationControl save = riskEvaluationControlDao.save(control);
        //更新大屏区域等级
        if (name.equals("动态安全风险评估")) {
            monitorPointDataWebSocketService.getDistrictList(null, "ALL", Context.getCompanyCode(), Context.getCurrentTenantId());
        }
        return save;
    }

    /**
     * 获取基础配置列表
     *
     * @return
     */
    @Override
    public List<RiskEvaluationControlBean> getControlList() {
        List<RiskEvaluationControl> all = riskEvaluationControlDao.findAll();
        List<RiskEvaluationControlBean> list = new ArrayList<>();
        for (RiskEvaluationControl control : all) {
            RiskEvaluationControlBean bean = new RiskEvaluationControlBean();
            bean.setLabel(control.getName());
            bean.setValue(control.getSwitchState());
            list.add(bean);
        }
        return list;
    }

    /**
     * 批量保存校正规则
     *
     * @param listBean
     * @return
     */
    @Override
    public void saveCorrectionRuleList(List<RiskEvaluationCorrectionRuleBean> listBean) {
        for (RiskEvaluationCorrectionRuleBean bean : listBean) {
            if (bean.getOrderNumber() == null) {
                throw new IllegalArgumentException("校正规则序号不能为空");
            }

            if (bean.getDeleteFlag() != null && bean.getDeleteFlag().intValue() == 0) {
                //删除
                if (bean.getId() != null) {
                    correctionRuleDao.deleteById(bean.getId());
                }
            } else {
                if (Math.abs(bean.getLevelChange()) > 4 && Math.abs(bean.getLevelChange()) < 1) {
                    throw new IllegalArgumentException("风险等级变化绝对值不能大于四且不能小于1");
                }
                RiskEvaluationCorrectionRule rule = null;
                if (bean.getId() == null) {
                    //新增
                    rule = new RiskEvaluationCorrectionRule();
                    BeanUtils.copyProperties(bean, rule);
                } else {
                    //修改
                    rule = correctionRuleDao.findById(bean.getId()).orElseThrow(() -> new IllegalArgumentException("第" + bean.getOrderNumber() + "项校正规则不存在"));
                    BeanUtils.copyProperties(bean, rule, "id");
                }
                RiskEvaluationCorrectionRule save = correctionRuleDao.save(rule);
                int count = correctionRuleDao.countByName(save.getName());
                if (count > 1) {
                    throw new IllegalArgumentException("第" + bean.getOrderNumber() + "项校正规则名称已存在");
                }
            }
        }

    }

    /**
     * 获取校正规则列表
     *
     * @return
     */
    @Override
    public List<RiskEvaluationCorrectionRuleBean> getCorrectionRuleList() {
        List<RiskEvaluationCorrectionRule> all = correctionRuleDao.findAll();
        List<RiskEvaluationCorrectionRuleBean> list = new ArrayList<>();
        for (RiskEvaluationCorrectionRule rule : all) {
            RiskEvaluationCorrectionRuleBean bean = new RiskEvaluationCorrectionRuleBean();
            BeanUtils.copyProperties(rule, bean);
            list.add(bean);
        }
        List<RiskEvaluationCorrectionRuleBean> collect = list.stream()
                .sorted(Comparator.comparing(RiskEvaluationCorrectionRuleBean::getOrderNumber, Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());
        return collect;
    }

    /**
     * 删除校正规则
     *
     * @param id
     */
    @Override
    public void deleteCorrectionRule(Long id) {
        correctionRuleDao.deleteById(id);
    }

    /**
     * 保存管控清单字段
     *
     * @param bean
     * @return
     */
    @Override
    public RiskEvaluationListField saveListField(RiskEvaluationListFieldBean bean) {
        RiskEvaluationListField field = null;
        if (StringUtils.isBlank(bean.getName())) {
            throw new IllegalArgumentException("名称不能为空");
        }
        if (bean.getId() == null) {
            //新增
            List<RiskEvaluationListField> all = listFieldDao.findAll();
            field = new RiskEvaluationListField();
            BeanUtils.copyProperties(bean, field);
            //排序从0开始,每增一个+1
            field.setOrderNumber(all.size());
            field.setCount(0);
        } else {
            //修改
            field = listFieldDao.findById(bean.getId()).orElseThrow(() -> new IllegalArgumentException("管控清单字段不存在"));
            BeanUtils.copyProperties(bean, field, "id", "orderNumber", "count");
        }
        RiskEvaluationListField save = listFieldDao.save(field);
        int count = listFieldDao.countByName(bean.getName());
        if (count > 1) {
            throw new IllegalArgumentException("该管控清单字段名称已存在");
        }
        return save;
    }

    /**
     * 删除管控清单字段
     *
     * @param id
     */
    @Override
    public void deleteListField(Long id) {
        int count = analyzeMethodDao.countByFieldId(id);
        if (count > 0) {
            throw new IllegalArgumentException("请先解除该清单字段和分析方法配置项的关联关系");
        }
        listFieldDao.deleteById(id);
    }

    /**
     * 获取管控清单字段列表
     *
     * @return
     */
    @Override
    public List<RiskEvaluationListFieldBean> getFieldList() {
        List<RiskEvaluationListField> all = listFieldDao.findAll();
        List<RiskEvaluationListFieldBean> list = new ArrayList<>();
        for (RiskEvaluationListField field : all) {
            RiskEvaluationListFieldBean bean = new RiskEvaluationListFieldBean();
            BeanUtils.copyProperties(field, bean);
            list.add(bean);
        }
        List<RiskEvaluationListFieldBean> collect = list.stream()
                .sorted(Comparator.comparing(RiskEvaluationListFieldBean::getOrderNumber, Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());
        return collect;
    }

    /**
     * 获取管控清单字段下拉列表
     *
     * @return
     */
    @Override
    public List<SimpleSelectListBean> getSelectFieldList() {
        List<RiskEvaluationListField> all = listFieldDao.findAll();
        List<SimpleSelectListBean> list = new ArrayList<>();
        for (RiskEvaluationListField field : all) {
            SimpleSelectListBean bean = new SimpleSelectListBean();
            bean.setLabel(field.getName());
            bean.setValue(field.getId());
            list.add(bean);
        }
        return list;
    }


    /**
     * 设置管控清单顺序
     *
     * @param upId
     * @param downId
     */
    @Override
    public void editFieldOrder(Long upId, Long downId) {
        RiskEvaluationListField upField = listFieldDao.findById(upId).orElseThrow(() -> new IllegalArgumentException("管控清单字段不存在"));
        RiskEvaluationListField downField = listFieldDao.findById(downId).orElseThrow(() -> new IllegalArgumentException("管控清单字段不存在"));
        int orderNumber = upField.getOrderNumber();
        upField.setOrderNumber(downField.getOrderNumber());
        downField.setOrderNumber(orderNumber);
        listFieldDao.save(upField);
        listFieldDao.save(downField);
    }

    /**
     * 保存方法配置
     *
     * @param bean
     * @return
     */
    @Override
    public RiskEvaluationAnalyzeWay saveAnalyzeWay(RiskEvaluationAnalyzeWayBean bean) {
        RiskEvaluationAnalyzeWay way = null;
        if (bean.getId() == null) {
            //新增
            way = new RiskEvaluationAnalyzeWay();
            BeanUtils.copyProperties(bean, way);
        } else {
            way = analyzeWayDao.findById(bean.getId()).orElseThrow(() -> new IllegalArgumentException("方法配置不存在"));
            if (way.getAnalyzeType() != null && bean.getAnalyzeType() != null && (!way.getAnalyzeType().equals(bean.getAnalyzeType()))) {
                throw new IllegalArgumentException("方法类型不可以切换");
            }
            BeanUtils.copyProperties(bean, way, "id");
        }
        //保存分析方法和评估方法
        RiskEvaluationAnalyzeWay save = analyzeWayDao.save(way);
        int co = analyzeWayDao.countByNameAndAnalyzeType(save.getName(), save.getAnalyzeType());
        int cou = analyzeWayDao.countByCodeAndAnalyzeType(save.getCode(), save.getAnalyzeType());
        if (co > 1) {
            throw new IllegalArgumentException("名称已存在");
        }
        if (cou > 1) {
            throw new IllegalArgumentException("简称已存在");
        }
        saveAnalyzeMethod(save, bean);
        return save;
    }

    //保存方法配置项
    private void saveAnalyzeMethod(RiskEvaluationAnalyzeWay way, RiskEvaluationAnalyzeWayBean wayBean) {
        List<RiskEvaluationAnalyzeMethodBean> methodBeanList = wayBean.getMethodBeanList();
        int a = 0;
        int b = 0;
        for (RiskEvaluationAnalyzeMethodBean bean : methodBeanList) {
            if (way.getAnalyzeType() != null && way.getAnalyzeType().intValue() == 1) {
                //对评估方法的
                if (bean.getContentType() != null && bean.getContentType().intValue() == 0) {
                    a++;
                } else if (bean.getContentType() != null && bean.getContentType().intValue() == 1) {
                    b++;
                }
            }
            if (bean.getDeleteFlag() != null && bean.getDeleteFlag().intValue() == 0) {
                //删除
                if (bean.getId() != null) {
                    deleteMethod(bean.getId());
                }
            } else {
                RiskEvaluationAnalyzeMethod method = null;
                if (bean.getId() == null) {
                    //新增
                    method = new RiskEvaluationAnalyzeMethod();
                    BeanUtils.copyProperties(bean, method);
                    //分析方法 更新管控清单字段数量
                    if (wayBean.getAnalyzeType() != null && wayBean.getAnalyzeType().intValue() == 0) {
                        Optional<RiskEvaluationListField> byId = listFieldDao.findById(bean.getFieldId());
                        if (byId.isPresent()) {
                            byId.get().setCount(byId.get().getCount() + 1);
                            listFieldDao.save(byId.get());
                        }
                    }
                    //更新
                } else {
                    //修改
                    method = analyzeMethodDao.findById(bean.getId()).orElseThrow(() -> new IllegalArgumentException("配置项不存在"));
                    //分析方法 更新管控清单字段数量
                    if (wayBean.getAnalyzeType() != null && wayBean.getAnalyzeType().intValue() == 0) {
                        if (!method.getFieldId().equals(bean.getFieldId())) {
                            Optional<RiskEvaluationListField> oldField = listFieldDao.findById(method.getFieldId());
                            Optional<RiskEvaluationListField> newField = listFieldDao.findById(bean.getFieldId());
                            if (oldField.isPresent()) {
                                oldField.get().setCount(oldField.get().getCount() - 1);
                                listFieldDao.save(oldField.get());
                            }
                            if (newField.isPresent()) {
                                newField.get().setCount(newField.get().getCount() + 1);
                                listFieldDao.save(newField.get());
                            }
                        }
                    }
                    BeanUtils.copyProperties(bean, method, "id");
                }
                //方法id
                method.setWayId(way.getId());
                //类型:0分析方法,1评估方法
                method.setAnalyzeType(wayBean.getAnalyzeType());
                RiskEvaluationAnalyzeMethod save = analyzeMethodDao.save(method);
                checkAnalyzeMethod(save);
            }
        }
        if (way.getAnalyzeType() != null && way.getAnalyzeType().intValue() == 1) {
            if (a < 1) {
                throw new IllegalArgumentException("乘数至少有一项");
            }
            if (b != 1) {
                throw new IllegalArgumentException("乘积有且只能有一项");
            }
        }
    }

    //删除配置项
    private void deleteMethod(Long methodId) {
        if (methodId != null) {
            RiskEvaluationAnalyzeMethod method = analyzeMethodDao.findById(methodId).orElseThrow(() -> new IllegalArgumentException("方法配置不存在"));
//            int cc = targetTypeDao.countByMethodId(methodId);
//            if (cc > 0) {
//                throw new IllegalArgumentException("请先删除关联的评估指标");
//            }
            //分析方法 更新管控清单字段数量
            if (method != null && method.getAnalyzeType() != null && method.getAnalyzeType().intValue() == 0 && method.getFieldId() != null) {
                Optional<RiskEvaluationListField> byId = listFieldDao.findById(method.getFieldId());
                if (byId.isPresent()) {
                    List<RiskEvaluationAnalyzeMethod> methodList = analyzeMethodDao.findByFieldId(method.getFieldId());
                    byId.get().setCount(methodList.size() - 1);
                    listFieldDao.save(byId.get());
                }
            }
            //删除指标类型指标
            List<RiskEvaluationTargetType> typeList = targetTypeDao.findByMethodId(methodId);
            for (RiskEvaluationTargetType type : typeList) {
                List<RiskEvaluationTargetItem> itemList = targetItemDao.findByTypeId(type.getId());
                for (RiskEvaluationTargetItem item : itemList) {
                    targetItemDao.deleteById(item.getId());
                }
                targetTypeDao.deleteById(type.getId());
            }
            analyzeMethodDao.deleteById(methodId);
        }
    }

    private void checkAnalyzeMethod(RiskEvaluationAnalyzeMethod save) {
        int count1 = analyzeMethodDao.countByNameAndWayId(save.getName(), save.getWayId());
        if (count1 > 1) {
            throw new IllegalArgumentException("配置项名称已存在");
        }
        //评估方法的一些判断
        if (save.getAnalyzeType() != null && save.getAnalyzeType().intValue() == 1) {
            if (save.getCode() != null) {
                int count2 = analyzeMethodDao.countByCodeAndWayId(save.getCode(), save.getWayId());
                if (count2 > 1) {
                    throw new IllegalArgumentException("配置项代号已存在");
                }
            }
        }
    }

    /**
     * 查看方法配置
     *
     * @param id
     * @return
     */
    @Override
    public RiskEvaluationAnalyzeWayBean findAnalyzeWay(Long id) {
        RiskEvaluationAnalyzeWayBean bean = new RiskEvaluationAnalyzeWayBean();
        RiskEvaluationAnalyzeWay way = analyzeWayDao.findById(id).orElseThrow(() -> new IllegalArgumentException("方法不存在"));
        BeanUtils.copyProperties(way, bean);
        if (way.getEvaluationId() != null && way.getAnalyzeType() != null && way.getAnalyzeType().intValue() == 0) {
            Optional<RiskEvaluationAnalyzeWay> reaw = analyzeWayDao.findById(way.getEvaluationId());
            if (reaw.isPresent()) {
                bean.setEvaluationName(reaw.get().getName() + "(" + reaw.get().getCode() + ")");
            }
        }
        //配置项
        List<RiskEvaluationAnalyzeMethodBean> methodBeanList = new ArrayList<>();
        List<RiskEvaluationAnalyzeMethod> list = analyzeMethodDao.findByWayId(id);
        for (RiskEvaluationAnalyzeMethod method : list) {
            RiskEvaluationAnalyzeMethodBean methodBean = new RiskEvaluationAnalyzeMethodBean();
            BeanUtils.copyProperties(method, methodBean);
            //清单名称
            if (method.getAnalyzeType() != null && method.getAnalyzeType().intValue() == 0 && method.getFieldId() != null) {
                Optional<RiskEvaluationListField> byId = listFieldDao.findById(method.getFieldId());
                if (byId.isPresent()) {
                    methodBean.setFieldName(byId.get().getName());
                }
            }
            methodBeanList.add(methodBean);
        }
        methodBeanList = methodBeanList.stream()
                .sorted(Comparator.comparing(RiskEvaluationAnalyzeMethodBean::getOrderNumber, Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());
        bean.setMethodBeanList(methodBeanList);
        return bean;
    }

    /**
     * 删除方法配置
     *
     * @param id
     */
    @Override
    public void deleteAnalyzeWay(Long id) {
        checkDeleteAnalyzeWay(id);
        analyzeWayDao.deleteById(id);
    }

    //根据方法配置id删除配置项
    private void checkDeleteAnalyzeWay(Long wayId) {
        List<RiskPointEvaluationBusiness> pbList = riskPointEvaluationBusinessDao.findByAnalyzeWayId(wayId);
        if (!CollectionUtils.isEmpty(pbList)) {
            throw new IllegalArgumentException("该分析方法已被使用,请勿删除");
        }
        //评估方法需要解绑
        List<RiskEvaluationAnalyzeWay> evList = analyzeWayDao.findByEvaluationId(wayId);
        if (!CollectionUtils.isEmpty(evList)) {
            throw new IllegalArgumentException("请先解除与分析方法的绑定关系");
        }
        List<RiskEvaluationAnalyzeMethod> methodList = analyzeMethodDao.findByWayId(wayId);
        for (RiskEvaluationAnalyzeMethod method : methodList) {
            deleteMethod(method.getId());
        }
    }

    /**
     * 获取配置方法列表
     *
     * @param analyzeType 0分析 ,1评估,2关联了评估方法的分析方发(风险点控制风险 选择方法列表),null 查所有
     * @return
     */
    @Override
    public List<SimpleSelectListBean> getAllAnalyzeWay(Integer analyzeType) {
        List<RiskEvaluationAnalyzeWay> all = new ArrayList<>();
        if (analyzeType == null) {
            all = analyzeWayDao.findAll();
        } else if (analyzeType.intValue() == 1 || analyzeType.intValue() == 0) {
            all = analyzeWayDao.getListByAnalyzeType(analyzeType);
        } else if (analyzeType.intValue() == 2) {
            all = analyzeWayDao.getPointAnalyzeWayList(0);
        }
        List<SimpleSelectListBean> list = new ArrayList<>();
        for (RiskEvaluationAnalyzeWay way : all) {
            SimpleSelectListBean bean = new SimpleSelectListBean();
            bean.setValue(way.getId());
            bean.setLabel(way.getName() + "(" + way.getCode() + ")");
            list.add(bean);
        }
        return list;
    }

    /**
     * 使用评估方法
     *
     * @param analyzeId    分析方法id
     * @param evaluationId 评估方法id
     * @return
     */
    @Override
    public RiskEvaluationAnalyzeWay editWayRelation(Long analyzeId, Long evaluationId) {
        if (analyzeId == null) {
            throw new IllegalArgumentException("分析方法不能为空");
        }
        //查找分析方法
        RiskEvaluationAnalyzeWay way = analyzeWayDao.findById(analyzeId).orElseThrow(() -> new IllegalArgumentException("该评估方法不存在"));
        if (way.getEvaluationId() != null) {
            throw new IllegalArgumentException("当前分析方法已与评估方法关联");
        }
        //保存评估方法id
        way.setEvaluationId(evaluationId);
        RiskEvaluationAnalyzeWay save = analyzeWayDao.save(way);
        return save;
    }

    /**
     * 保存评估指标
     *
     * @param list
     * @return
     */
    @Override
    public void saveEvaluetionTarget(List<RiskEvaluationTargetTypeBean> list) {
        for (RiskEvaluationTargetTypeBean bean : list) {
            if (bean.getDeleteFlag() != null && bean.getDeleteFlag().intValue() == 0) {
                if (bean.getId() != null) {
                    if (list.size() > 1 && StringUtils.isBlank(bean.getName())) {
                        throw new IllegalArgumentException("多类型评估,评估名称不能为空");
                    }
                    //删除
                    targetTypeDao.deleteById(bean.getId());
                    List<RiskEvaluationTargetItemBean> itemBeans = bean.getBeanList();
                    for (RiskEvaluationTargetItemBean itemBean : itemBeans) {
                        if (itemBean.getId() != null) {
                            targetItemDao.deleteById(itemBean.getId());
                        }
                    }
                }
            } else {
                RiskEvaluationTargetType type = null;
                if (bean.getId() == null) {
                    //新增
                    type = new RiskEvaluationTargetType();
                    BeanUtils.copyProperties(bean, type);
                } else {
                    //修改
                    type = targetTypeDao.findById(bean.getId()).orElseThrow(() -> new IllegalArgumentException("评估指标类型不存在"));
                    BeanUtils.copyProperties(bean, type, "id");
                }
                if (bean.getName() == null) {

                }
                RiskEvaluationTargetType save = targetTypeDao.save(type);
                int co = targetTypeDao.countByNameAndMethodId(save.getName(), save.getMethodId());
                if (co > 1) {
                    throw new IllegalArgumentException("类型名称已存在");
                }
                saveTargetItem(save.getId(), bean);
            }
        }
    }


    //保存指标内容
    private void saveTargetItem(Long typeId, RiskEvaluationTargetTypeBean bean) {
        List<RiskEvaluationTargetItemBean> beanList = bean.getBeanList();
        for (RiskEvaluationTargetItemBean itemBean : beanList) {
            if (itemBean.getDeleteFlag() != null && itemBean.getDeleteFlag().intValue() == 0) {
                //删除
                if (itemBean.getId() != null) {
                    targetItemDao.deleteById(itemBean.getId());
                }
            } else {
                RiskEvaluationTargetItem item = null;
                if (itemBean.getId() == null) {
                    //新增
                    item = new RiskEvaluationTargetItem();
                    BeanUtils.copyProperties(itemBean, item);
                    item.setTypeId(typeId);
                } else {
                    //修改
                    item = targetItemDao.findById(itemBean.getId()).orElseThrow(() -> new IllegalArgumentException("指标内容不存在"));
                    BeanUtils.copyProperties(itemBean, item, "id");
                }
                RiskEvaluationTargetItem save = targetItemDao.save(item);
                int count = targetItemDao.countByNameAndTypeId(save.getName(), save.getTypeId());
                if (count > 1) {
                    throw new IllegalArgumentException("指标内容已存在");
                }
            }
        }
    }

    /**
     * 获取评估指标
     *
     * @param methodId
     * @return
     */
    @Override
    public ResultBean getTargetList(Long methodId) {
        List<RiskEvaluationTargetType> typeList = targetTypeDao.findByMethodId(methodId);
        List<RiskEvaluationTargetTypeBean> list = new ArrayList<>();
        for (RiskEvaluationTargetType type : typeList) {
            RiskEvaluationTargetTypeBean typeBean = new RiskEvaluationTargetTypeBean();
            BeanUtils.copyProperties(type, typeBean);
            List<RiskEvaluationTargetItemBean> itemList = getTargetItemBeanByTypeId(type.getId());
            itemList = itemList.stream()
                    .sorted(Comparator.comparing(RiskEvaluationTargetItemBean::getOrderNumber, Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());
            typeBean.setBeanList(itemList);
            list.add(typeBean);
        }

        return ResultBean.success(list);
    }

    //根据指标类型id获取指标内容
    private List<RiskEvaluationTargetItemBean> getTargetItemBeanByTypeId(Long typeId) {
        List<RiskEvaluationTargetItem> list = targetItemDao.findByTypeId(typeId);
        List<RiskEvaluationTargetItemBean> beanList = new ArrayList<>();
        for (RiskEvaluationTargetItem item : list) {
            RiskEvaluationTargetItemBean bean = new RiskEvaluationTargetItemBean();
            BeanUtils.copyProperties(item, bean);
            beanList.add(bean);
        }
        return beanList;
    }

    @Override
    public List<RiskDynamicConfig> dynamicRiskSave(RiskDynamicConfigBatchSaveVo vo) {
        List<RiskDynamicConfig> configs = new ArrayList<>();
        if (!CollectionUtils.isEmpty(vo.getVoList())) {
            //删除未检任务触发动态风险缓存
            removeUnCheckDynamicRiskCache();
            vo.getVoList().forEach(data -> {
                int count = 0;
                RiskDynamicConfig config = new RiskDynamicConfig();
                if (data.getId() != null) {
                    config = riskDynamicConfigDao.findById(data.getId()).orElseThrow(() -> new IllegalArgumentException("该配置项不存在"));
                    count = riskDynamicConfigDao.countByProcessIdAndOptionTypeNameAndOptionParamIdAndTypeAndIdNotEq(data.getProcessId(), data.getOptionTypeName(), data.getOptionParamId(), data.getType(), data.getId());
                } else {
                    count = riskDynamicConfigDao.countByProcessIdAndOptionTypeNameAndOptionParamIdAndType(data.getProcessId(), data.getOptionTypeName(), data.getOptionParamId(), data.getType());
                }
                if (count > 1) {
                    throw new IllegalArgumentException(data.getBusinessName() + " 的配置信息已存在");
                }
                BeanUtils.copyProperties(data, config);
                String node = "";
                if (!CollectionUtils.isEmpty(data.getNodeList())) {
                    node = JSON.toJSONString(data.getNodeList());
                }
                config.setNode(node);
                config = riskDynamicConfigDao.save(config);
                configs.add(config);
            });
            riskDynamicConfigDao.saveAll(configs);
        }
        if (!CollectionUtils.isEmpty(vo.getDeleteIds())) {
            vo.getDeleteIds().forEach(e -> {
                riskDynamicConfigDao.deleteById(e);
            });
        }
        RiskEvaluationControl control = riskEvaluationControlDao.findByName(Constants.UNCHECKED_TASK_TRIGGER_DYNAMIC_RISK);
        if (control != null) {
            control.setSwitchState(vo.getRiskSwitch());
            riskEvaluationControlDao.save(control);
        }
        return configs;
    }


    private void removeUnCheckDynamicRiskCache() {
        redisClient.removeMapKey(builderRiskControlKey(), BaseConfigCodes.RISK_EVALUATION_CONTROL_HASH_KEY);
    }

    @Override
    public RiskEvaluationControl getRiskEvControlFromRedis() {
        RiskEvaluationControl control = redisClient.hget(builderRiskControlKey(), BaseConfigCodes.RISK_EVALUATION_CONTROL_HASH_KEY, RiskEvaluationControl.class);
        if (control == null || control.getSwitchState() == null) {
            control = riskEvaluationControlDao.findByName(Constants.UNCHECKED_TASK_TRIGGER_DYNAMIC_RISK);
            if (control == null) {
                log.error("获取未检任务触发动态风险配置为空");
                return null;
            }
            // 若配置开关为null, 则更新为默认值, 开启
            if (control.getSwitchState() == null) {
                control.setSwitchState(1);
                riskEvaluationControlDao.save(control);
            }
            Long tenantId = control.getTenentId();
            String orgCode = control.getOrgCode();
            String redisKey = String.format(BaseConfigCodes.RISK_EVALUATION_CONTROL_REDIS_KEY, tenantId, orgCode);
            redisClient.hput(redisKey, BaseConfigCodes.RISK_EVALUATION_CONTROL_HASH_KEY, JSON.toJSONString(control,true));
        }
        return control;
    }

    private String builderRiskControlKey() {
        Long tenantId = Context.getCurrentTenantId();
        String orgCode = Context.getCurrentOrgCode();
        return String.format(BaseConfigCodes.RISK_EVALUATION_CONTROL_REDIS_KEY, tenantId, orgCode);
    }

    @Override
    public List<RiskDynamicConfigDto> getDynamicConfig() {
        List<RiskDynamicConfigDto> dtoList = new ArrayList<>();
        List<RiskDynamicConfig> all = riskDynamicConfigDao.findAll();
        if (!CollectionUtils.isEmpty(all)) {
            all.forEach(config -> {
                dtoList.add(convertDynamicConfigDto(config));
            });
        }
        return dtoList;
    }

    @Override
    public void deleteDynamicConfigById(Long id) {
        riskDynamicConfigDao.deleteById(id);
    }

    @Override
    public List<RiskDyncmicOptionTypeBean> getFormJsonByProcessId(Long processId) {
        List<RiskDyncmicOptionTypeBean> dataList = new ArrayList<>();
        WorkFlowProcess process = workFlowProcessDao.findById(processId).orElseThrow(() -> new IllegalArgumentException("该业务不存在"));
        String formJsonStr = process.getFormJson();
        if (StringUtils.isBlank(formJsonStr)) {
            return dataList;
        }
        JSONObject fromJson = JSON.parseObject(formJsonStr);
        Object temArrObj = fromJson.get(WorkFlowConstants.FROM_JSON_KEY_TEMARR);
        if (temArrObj == null) {
            return dataList;
        }
        JSONArray temArr = JSONObject.parseArray(temArrObj.toString());
        for (Object tem : temArr) {
            Map<String, Object> tableMap = JSONObject.parseObject(JSON.toJSONString(tem));
            Object tableArrObj = tableMap.get(WorkFlowConstants.FROM_JSON_KEY_TABLEARR);
            if (tableArrObj == null) {
                continue;
            }
            JSONArray tableArr = JSONObject.parseArray(tableArrObj.toString());
            for (Object table : tableArr) {
                Map<String, Object> beanMap = JSONObject.parseObject(JSON.toJSONString(table));
                Object labelObj = beanMap.get(WorkFlowConstants.FROM_JSON_KEY_LABEL);
                if (labelObj == null) {
                    continue;
                }
                String value = (String) labelObj;
                if (!value.contains("级别") && !value.contains("等级")) {
                    continue;
                }
                Object valueObj = beanMap.get(WorkFlowConstants.FROM_JSON_KEY_LIST);
                if (valueObj == null || !(valueObj instanceof java.lang.String)) {
                    continue;
                }
                String optionTypeProxyName = (String) valueObj;
                WorkFlowOptionType type = workFlowOptionTypeDao.findByName(optionTypeProxyName);
                if (type != null) {
                    RiskDyncmicOptionTypeBean bean = new RiskDyncmicOptionTypeBean();
                    bean.setOptionTypeName(value);
                    bean.setOptionTypeProxyName(optionTypeProxyName);
                    bean.setOptionTypeProxyId(type.getId());
                    dataList.add(bean);
                }
            }
        }
        return dataList;
    }

    private RiskDynamicConfigDto convertDynamicConfigDto(RiskDynamicConfig config) {
        RiskDynamicConfigDto dto = new RiskDynamicConfigDto();
        BeanUtils.copyProperties(config, dto);
        if (config.getProcessId() != null) {
            WorkFlowProcess process = workFlowProcessDao.findById(config.getProcessId()).orElseThrow(() -> new IllegalArgumentException("该流程已被删除"));
            dto.setBusinessName(process.getBizName());
        }
        if (config.getOptionParamId() != null) {
            WorkFlowOption option = workFlowOptionDao.findById(config.getOptionParamId()).orElseThrow(() -> new IllegalArgumentException("该参数已被删除"));
            dto.setOptionParamName(option.getOptionName());
        }
        List<String> nodeList = new ArrayList<>();
        if (StringUtils.isNotBlank(config.getNode())) {
            nodeList = JSONArray.parseArray(config.getNode(), String.class);
        }
        dto.setNodeList(nodeList);
        return dto;
    }

}
